package com.volunteer.controller.admin;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.volunteer.common.R;
import com.volunteer.entity.User;
import com.volunteer.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/user")
@AllArgsConstructor
public class AdminUserController {

    private final UserService userService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public R<List<User>> list() {
        List<User> list = userService.list(new LambdaQueryWrapper<User>().orderByAsc(User::getId));
        return R.ok(list);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody User user) {
        // 初始密码
        user.setPassword(BCrypt.hashpw("123456"));
        boolean success = userService.save(user);
        return success ? R.ok("新增成功") : R.fail("新增失败");
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody User user) {
        boolean success = userService.updateById(user);
        return success ? R.ok("更新成功") : R.fail("更新失败");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete/{id}")
    public R<String> delete(@PathVariable Long id) {
        boolean success = userService.removeById(id);
        return success ? R.ok("删除成功") : R.fail("删除失败");
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/get/{id}")
    public R<User> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        return user != null ? R.ok(user) : R.fail("未找到该用户");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody User user) {
        // 这里可以根据用户名和密码进行验证，返回token等
        return R.ok("登录成功");
    }

}
